//
//  PhotoAlbumTableViewCell.swift
//  MQAlbum
//
//  Created by 许博 on 2017/4/10.
//  Copyright © 2017年 mechat. All rights reserved.
//

import UIKit
import Photos

class PhotoAlbumTableViewCell: UITableViewCell {


   
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        contentView.addSubview(albumCover)
        contentView.addSubview(albumTitle)
        contentView.addSubview(albumNumber)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutMargins = UIEdgeInsets.zero
        let bgView = UIView()
        bgView.backgroundColor = UIColor.init(red: 1, green: 0, blue: 0, alpha: 0.5)
        self.selectedBackgroundView = bgView
        
        albumCover.frame = CGRect(x: 10, y: 10, width: 70, height: 70)
        albumTitle.frame = CGRect(x: 100, y: 15, width: 200, height: 25)
        albumNumber.frame = CGRect(x: 100, y: 45, width: 200, height: 25)
    }
    
    
    let imageSize: CGFloat = 80
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }
    
    
    func renderData(result:PHFetchResult<AnyObject>, label: String?){
        self.albumTitle.text = label
        self.albumNumber.text = String(result.count)
        
        if result.count > 0 {
            if let firstImageAsset = result[0] as? PHAsset {
                let retinaMultiplier = UIScreen.main.scale
                let realSize = self.imageSize * retinaMultiplier
                let size = CGSize(width:realSize, height: realSize)
                
                let imageOptions = PHImageRequestOptions()
                imageOptions.resizeMode = .exact
                
                PHImageManager.default().requestImage(for: firstImageAsset, targetSize: size, contentMode: .aspectFill, options: imageOptions, resultHandler: { (image, info) -> Void in
                    self.albumCover.image = image
                })
            }
        }
    }
    
    private lazy var albumCover:UIImageView = UIImageView()
    private lazy var albumTitle:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 17)
        label.textColor = UIColor.black
        return label
    }()
    private lazy var albumNumber:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor.darkGray
        return label
    }()
    

}
